package com.starblink.login.signin.ui

import android.app.Activity
import android.content.Intent
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.starblink.android.basic.base.BaseViewModel
import com.starblink.android.basic.ext.toast
import com.starblink.android.basic.network.base.SkGqlClient
import com.starblink.android.basic.user.login.LoginManager
import com.starblink.basic.style.R
import com.starblink.basic.util.ActivityStackManage
import com.starblink.basic.util.CommUtils
import com.starblink.basic.util.log.YYLogUtils
import com.starblink.rocketreserver.ThirdLoginMutation
import com.starblink.rocketreserver.type.LoginChannel
import kotlinx.coroutines.launch


class SigninVM : BaseViewModel() {
    val linkSocialGuangAccountLiveData: MutableLiveData<ThirdLoginMutation.ThirdLoginAccountV2> =
        MutableLiveData()

    fun loginWithThirdParty(loginChannel: LoginChannel, accessToken: String) {
        viewModelScope.launch {
            // 调用我们的三方登录接口进行登录
            val response = SkGqlClient.skMutation(
                ThirdLoginMutation(
                    channel = loginChannel,
                    thirdToken = accessToken,
                ),
                showDefaultLoading = true
            )
            if (response?.data != null) {
                if (response.data!!.thirdLoginAccountV2.loginSuccess) {
                    // 三方登录成功，更新token，获取账户信息
                    if (response.data!!.thirdLoginAccountV2.guangToken.isNullOrEmpty()) {
                        toast(CommUtils.getString(R.string.login_fail))
                        return@launch
                    }
                    LoginManager.refreshTokenAndUserInfoAfterLoginSuccess(
                        response.data!!.thirdLoginAccountV2.guangToken!!,
                        onSuccess = {
                            YYLogUtils.e("refreshTokenAndUserInfoAfterLoginSuccess成功，登录成功", "dss")
                            toast(R.string.login_success)
                            // 设置登录成功返回值，返回登录前页面
                            ActivityStackManage.currentActivity()
                                .setResult(Activity.RESULT_OK, Intent().putExtra("isLogin", true))
                            ActivityStackManage.currentActivity().finish()
                        },
                        onFail = {
                            YYLogUtils.e("refreshTokenAndUserInfoAfterLoginSuccess失败", "dss")
                            toast(CommUtils.getString(R.string.login_fail))
                        }
                    )
                } else {
                    // 三方登录不完全成功，loginSuccess=false, 需要将三方账号和Guang账号绑定
                    linkSocialGuangAccountLiveData.postValue(response.data!!.thirdLoginAccountV2)
                }
            } else {
                // 三方登录失败
                YYLogUtils.e("ThirdLoginMutation失败", "dss")
                toast(CommUtils.getString(R.string.login_fail))
            }
        }
    }
}